package day_2022_7_to_8.day48;

/**
 * @author haomin
 * @date 2022/08/04 15:30
 **/
public class Day20_2_Num8_MyAtoi {
    public static void main(String[] args) {
        System.out.println(myAtoi("-abc"));
    }


    public static int myAtoi(String s) {
        StringBuilder res = new StringBuilder();
        s = s.trim();
        if(s.length() == 0)return 0;  // []情况
        if(s.length() == 1 && !Character.isDigit(s.charAt(0))) return 0;  // [+]情况
        char a = ' ';
        for(int i = 0;i < s.length();i++){
            if(s.charAt(i) == '+' || s.charAt(i) == '-'){
                if ((i+1) < s.length() && !Character.isDigit(s.charAt(i+1))) return 0; // [+-123]情况
                a = s.charAt(i);
                // [+12345abc]情况
                while ((i+1) < s.length() && Character.isDigit(s.charAt(i+1))){
                    res.append(s.charAt(i + 1));
                    i++;
                }
                break;
            } else if(Character.isDigit(s.charAt(i))){
                res.append(s.charAt(i));
                // [12345abc]情况
                while ((i+1) < s.length() && Character.isDigit(s.charAt(i+1))){
                    res.append(s.charAt(i + 1));
                    i++;
                }
                break;
            }else return 0;
        }
        try {
            long result = Long.parseLong(res.toString());  // 字符转化为长整型可能溢出
            // long未溢出
            if(a == '-') result = -result;
            if(result > Math.pow(2,31)-1) return (int) (Math.pow(2,31)-1);
            else if(result < -Math.pow(2,31)) return (int) (-Math.pow(2,31));
            else return (int)result;
        }catch (Exception e){  // long溢出，超出long范围，捕获异常
            if(a == '-') return (int) (-Math.pow(2,31));
            else return (int) (Math.pow(2,31)-1);
        }
    }
}